package com.kly.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.kly.exception.BusinessException;
import com.kly.exception.ErrorCode;
import com.kly.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author admin
 * @date 2025/3/5
 */
@Service
public class FilePictureUpload extends PictureUploadTemplate {
    @Override
    protected File processFile(Object inputSource, File tempFile) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        try {
            multipartFile.transferTo(tempFile);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return tempFile;
    }

    @Override
    protected String getOriginalName(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void validatePictureInfo(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        // 校验文件大小
        long size = multipartFile.getSize();
        ThrowUtils.throwIf(size > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
        //     检验文件名称后缀
        String fileName = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(fileName);
        ThrowUtils.throwIf(!IMAGE_FORMATS.contains(suffix), ErrorCode.PARAMS_ERROR, "不支持的文件格式");
    }
}
